package models

import (
	"strconv"
	"time"
	"xxp_api/utils"
)

type Order struct {
	Id           int
	Order_number string
	Status       int
	Created      int
	Title        string
	Thumb        string
	Price        float64
	Commission   float64
	Mobile       string
	Profile_img  string
	Name         string
	Add_mobile   string
	Province     string
	City         string
	Address      string
}

func OrderList(uid, types, status, keystart int) (res Response) {
	var lists List
	//获取用户店铺id
	var shop_id int
	var order []Order
	ormer.Raw("select id from xxp_shop where kol_id=?", uid).QueryRow(&shop_id)
	sql := "SELECT o.id, o.order_number,o.status,o.created,g.title,g.thumb,g.price,g.commission,u.mobile,u.profile_img,ua.name,ua.mobile as add_mobile,ua.province,ua.city,ua.address FROM `xxp_orders` o LEFT JOIN xxp_user u ON o.uid = u.id LEFT JOIN xxp_goods g ON o.goods_id=g.id LEFT JOIN xxp_user_address ua ON ua.id = o.address_id WHERE 1 "
	sql += "AND o.goods_type=? AND o.shop_id = ? "
	if status > 0 {
		sql += " AND o.status=" + strconv.Itoa(status)
	}
	ormer.Raw(sql+" ORDER BY o.created DESC LIMIT ?,10 ", types, shop_id, 10*keystart).QueryRows(&order)
	if len(order) > 0 {
		lists.List = order
	} else {
		lists.List = []string{}
	}
	keystart = keystart + 1
	//判断是否有下一页
	var a []Order
	n, _ := ormer.Raw(sql+" ORDER BY o.created DESC LIMIT ?,10 ", types, shop_id, 10*keystart).QueryRows(&a)
	if n > 0 {
		lists.Hasnext = 1
	}
	lists.Keystart = keystart
	res.Data = lists
	return
}

func FindDay(types int) int64 {
	if types == 1 {
		now := time.Now()
		offset := int(time.Monday - now.Weekday())
		if offset > 0 {
			offset = -6
		}
		weekStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
		return weekStart.Unix()
	} else {
		now := time.Now()
		return time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location()).Unix()
	}

}

type statistic struct {
	Amount  int
	Balance float64
	Reback  float64
	Income  float64
	Rebate  float64
}

func OrderStatistic(uid, types, time1 int) (res Response) {
	var start int64
	var shop_id int
	ormer.Raw("select id from xxp_shop where kol_id=?", uid).QueryRow(&shop_id)
	switch time1 {
	case 1:
		start = FindDay(2)
	case 2:
		start = FindDay(1)
	case 3:
		start = time.Now().Unix() - 24*3600*30
	}
	sql := "SELECT COUNT(o.id) as amount,SUM(o.price) as balance,SUM(g.commission) as rebate FROM `xxp_orders` o,xxp_goods g where g.id = o.goods_id  "
	if types > 0 {
		sql += "AND o.goods_type = " + strconv.Itoa(types)
	}
	var data statistic
	ormer.Raw(sql+" AND o.created > ? AND o.shop_id = ?", start, shop_id).QueryRow(&data)
	data.Income = utils.Round(data.Rebate, 2)

	res.Data = statistic{
		Income:  utils.Round(data.Rebate, 2),
		Balance: utils.Round(data.Balance, 2),
		Amount:  data.Amount,
		Reback:  utils.Round(data.Reback, 2),
		Rebate:  utils.Round(data.Rebate, 2),
	}
	return
}
